package com.darkness.rpc.framework.protocol.http;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.darkness.rpc.framework.common.Invocation;
import com.darkness.rpc.framework.protocol.RequestHandler;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpEntityEnclosingRequestBase;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;

import java.io.InputStream;
import java.io.ObjectInputStream;
import java.net.URI;
import java.util.Collections;

/**
 * @author darkness
 * @time 2022/4/15 13:34
 * @description
 */
public class HttpRequestHandler implements RequestHandler {
    @Override
    public Object handleRequest(String ip, Integer port, Invocation request, Class<?> returnType) {
        CloseableHttpClient client = null;
        try {
            client = HttpClients.createDefault();
            HttpEntityEnclosingRequestBase base = new HttpEntityEnclosingRequestBase() {
                @Override
                public String getMethod() {
                    return "get";
                }
            };
            JSONObject entityJson = new JSONObject();
            entityJson.put("interfaceName", request.getInterfaceName());
            entityJson.put("methodName", request.getMethodName());
            JSONArray pTypes = new JSONArray();
            Class<?>[] parameterTypes = request.getParamTypes();
            for (Class<?> parameterType : parameterTypes) {
                pTypes.add(parameterType.getName());
            }
            entityJson.put("paramTypes", pTypes);
            JSONArray as = new JSONArray();
            Object[] args = request.getArgs();
            Collections.addAll(as, args);
            entityJson.put("args", as);
            entityJson.put("group", request.getGroup());
            entityJson.put("version", request.getVersion());
            base.setURI(URI.create("http://" + ip + ":" + port));
            HttpEntity entity = new StringEntity(entityJson.toJSONString(), ContentType.APPLICATION_JSON);
            base.setEntity(entity);
            CloseableHttpResponse execute = client.execute(base);
            InputStream content = execute.getEntity().getContent();
            ObjectInputStream in = new ObjectInputStream(content);
            return returnType.cast(in.readObject());
        } catch (Exception e) {
            e.printStackTrace();
        } finally {

            if (client != null) {
                try {
                    client.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

        }
        return null;
    }
}
